import 'dart:convert';
import 'dart:typed_data';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:get/get.dart';

// 加密服务
class EncryptionService extends GetxService {
  // 单例
  static EncryptionService get to => Get.find();

  // 使用更安全的密钥管理方式
  final String _encryptionKey = "5e5009171aaa489898f46a7a844c6432";

  // 验证密钥长度
  void _validateKey() {
    if (_encryptionKey.length != 32) {
      throw ArgumentError(
          'Encryption key must be 32 characters long for AES-256');
    }
  }

  // 优化后的加密函数
  String encryptString(String content) {
    if (content.isEmpty) {
      throw ArgumentError('Content cannot be empty');
    }

    _validateKey();

    try {
      // 使用更安全的随机数生成
      final iv = encrypt.IV.fromSecureRandom(16);

      // 创建加密器 - 使用更安全的模式
      final encrypter = encrypt.Encrypter(
        encrypt.AES(
          encrypt.Key.fromUtf8(_encryptionKey),
          mode: encrypt.AESMode.ctr, // CTR 模式是合适的
        ),
      );

      // 加密数据
      final encrypted = encrypter.encrypt(content, iv: iv);

      // 组合 IV 和密文
      final result = Uint8List(iv.bytes.length + encrypted.bytes.length)
        ..setAll(0, iv.bytes)
        ..setAll(iv.bytes.length, encrypted.bytes);

      return base64.encode(result);
    } catch (e) {
      throw Exception('Encryption failed: $e');
    }
  }

  // 对应的解密函数
  String decryptString(String encryptedBase64) {
    if (encryptedBase64.isEmpty) {
      throw ArgumentError('Encrypted data cannot be empty');
    }

    _validateKey();

    try {
      // 解码 Base64
      final encryptedData = base64.decode(encryptedBase64);

      if (encryptedData.length < 16) {
        throw ArgumentError('Invalid encrypted data: too short');
      }

      // 提取 IV (前16字节) 和密文
      final iv = encrypt.IV(encryptedData.sublist(0, 16));
      final cipherText = encrypt.Encrypted(encryptedData.sublist(16));

      // 创建解密器
      final encrypter = encrypt.Encrypter(
        encrypt.AES(
          encrypt.Key.fromUtf8(_encryptionKey),
          mode: encrypt.AESMode.ctr,
        ),
      );

      // 解密
      return encrypter.decrypt(cipherText, iv: iv);
    } catch (e) {
      throw Exception('Decryption failed: $e');
    }
  }
}
